import React, { Component } from 'react'

//创建Context对象
const MyContext = React.createContext()
const {Provider, Consumer} = MyContext
export default class Demo extends Component {
  state = {username: 'tom', age: 18}
  render() {
    const {username} = this.state
    return (
      <div>
         <h2>Demo...</h2>
         <h4>我的用户名是{username}</h4>
         <Provider value={{...this.state}}>
            <B/>
         </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div>
        B...
        <C/>
        <D/>
      </div>
    )
  }
}

class C extends Component {
  // 声明接收Context
  static contextType = MyContext
  render() {
    return (
      <div>
        C...
        <h4>我从A组件接收到的用户名是{this.context.username} --- {this.context.age}</h4>
      </div>
    )
  }
}

function D(){
  return (
    <div>
      D...
      <h4>我从A组件接收到的用户名是
      <Consumer>
          {
            value => {
              return `${value.username} --- ${value.age}`
            }
          }
        </Consumer>
      </h4>
    </div>
  )
}

